package com.brsya.movie.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.viewpager.widget.PagerAdapter;

import com.brsya.base.base.Contents;
import com.brsya.base.bean.MovieListBean;
import com.brsya.base.util.GlideUtil;
import com.brsya.base.util.LoggerUtil;
import com.brsya.movie.R;
import com.brsya.movie.constant.Constant;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Brsya
 * CreateDate: 2022/7/6  11:25
 * Description:
 * banner的ViewPager适配器
 */
public class BannerAdapter extends PagerAdapter {
    private final Activity context;
    private List<MovieListBean.BannerListDTO> bannerList;

    private final List<View> viewList;
    private OnItemClickListener<MovieListBean.BannerListDTO> itemListener;

    private View adView;

    private ViewGroup adViewBox;

    private boolean isChange = false;

    public BannerAdapter(Activity context) {
        this.context = context;
        viewList = new ArrayList<>();
        bannerList = new ArrayList<>();
        loadAd();
    }

    public List<MovieListBean.BannerListDTO> getBannerList() {
        return bannerList;
    }

    public void setBannerList(List<MovieListBean.BannerListDTO> dataList) {
        bannerList.clear();
        this.bannerList.addAll(dataList);
        adViewBox = null;

        if (bannerList.size() == 0) {
            return;
        }

        // 添加广告
        bannerList.add(1, null);
        notifyDataSetChanged();
    }

    /**
     * 加载广告
     */
    private void loadAd() {
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(context);
        float width = context.getApplicationContext().getResources().getDisplayMetrics().xdpi;
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(Contents.AD_TT_SDK_BANNER) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1
                .setExpressViewAcceptedSize(width * 5 / 6, 0) //期望模板广告view的size,单位dp
                .setAdLoadType(TTAdLoadType.LOAD)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
                .build();

        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            //请求失败回调
            @Override
            public void onError(int code, String message) {
                LoggerUtil.e("banner广告加载失败" + code + "--ss--" + message);
            }

            //请求成功回调
            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                LoggerUtil.e("banner广告加载成功");
                for (TTNativeExpressAd adBean : ads) {
                    adView = adBean.getExpressAdView();
                    if (adViewBox != null) {
                        adViewBox.addView(adView);
                        LoggerUtil.e("banner广告添加成功");
                    }
                    adBean.render();
                    adBean.setDislikeCallback(context, new TTAdDislike.DislikeInteractionCallback() {
                        @Override
                        public void onShow() {
                            if (bannerList.size() > 1 && bannerList.get(1) == null) {
                                bannerList.remove(1);
                            }
                            if (viewList.size() > 1) {
                                viewList.remove(1);
                                LoggerUtil.e("删除广告");
                            }
                            isChange = true;
                            notifyDataSetChanged();
                            if (itemListener != null) {
                                itemListener.adClose();
                            }
                        }

                        @Override
                        public void onSelected(int i, String s, boolean b) {

                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                    break;
                }

            }
        });
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        if (isChange) {
            LoggerUtil.e("刷新");
            return PagerAdapter.POSITION_NONE;
        }
        LoggerUtil.e("不刷新");
        return POSITION_UNCHANGED;
    }

    @Override
    public int getCount() {
        return bannerList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View rootView = LayoutInflater.from(context).inflate(R.layout.item_pager_banner, null, false);
        viewList.add(rootView);

        ViewGroup flAdBox = rootView.findViewById(R.id.fl_ad_box);
        ConstraintLayout clBannerBox = rootView.findViewById(R.id.cl_banner_box);
        ImageView ivImage = rootView.findViewById(R.id.iv_image);
        TextView tvText = rootView.findViewById(R.id.tv_text);

        MovieListBean.BannerListDTO bean;
        if (position >= bannerList.size()) {
            return rootView;
        }
        bean = bannerList.get(position);
        if (bean == null) {
            clBannerBox.setVisibility(View.GONE);
            flAdBox.setVisibility(View.VISIBLE);
            if (adView != null) {
                if (adViewBox != null) {
                    adViewBox.removeView(adView);
                }
                if (flAdBox.indexOfChild(adView) == -1) {
                    flAdBox.addView(adView);
                }
            } else {
                LoggerUtil.e("未请求到banner广告");
                adViewBox = flAdBox;
            }
        } else {
            clBannerBox.setVisibility(View.VISIBLE);
            flAdBox.setVisibility(View.GONE);
            GlideUtil.loadRound(ivImage, bean.getImgUrl(), 6);
            tvText.setText(bean.getTitle());
            int finalI = position;
            clBannerBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (itemListener == null) {
                        return;
                    }
                    itemListener.onItemClick(finalI, bean);
                }
            });
        }

        if (position == bannerList.size() - 1) {
            isChange = false;
        }

        container.addView(rootView);
        return rootView;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {

        container.removeView(viewList.get(position));
    }


    /**
     * 设置单个item点击事件
     *
     * @param listener 点击事件
     */
    public void setOnItemClickListener(OnItemClickListener<MovieListBean.BannerListDTO> listener) {
        itemListener = listener;
    }


    /**
     * 单个item点击事件
     *
     * @param <T> recyclerView中的数据泛型
     */
    public interface OnItemClickListener<T> {
        void onItemClick(int position, T data);

        void adClose();
    }
}
